package com.ruoyi.web.controller.system;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jeequan.jeepay.JeepayClient;
import com.jeequan.jeepay.exception.JeepayException;
import com.jeequan.jeepay.model.PayOrderCreateReqModel;
import com.jeequan.jeepay.model.PayOrderQueryReqModel;
import com.jeequan.jeepay.request.PayOrderCreateRequest;
import com.jeequan.jeepay.request.PayOrderListRequest;
import com.jeequan.jeepay.response.PayOrderCreateResponse;
import com.jeequan.jeepay.response.PayOrderListResponse;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.PayOrderCreateReq;
import com.ruoyi.common.core.domain.entity.QueryParams;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TcyPlatformOrder;
import com.ruoyi.system.service.ICarPayService;
import com.ruoyi.system.service.ITcyPlatformOrderService;
import com.ruoyi.system.third.constant.SysConstant;
import com.ruoyi.system.third.dto.PaymentDTO;
import com.ruoyi.system.third.service.ILiantuofuService;
import com.ruoyi.web.controller.common.CommonController;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 停车缴费管理Controller
 *
 * @author ruoyi
 * @date 2024-09-10
 */
@RestController
@RequestMapping("/system/carPay")
public class CarPayController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ICarPayService carPayService;

    @Resource
    ILiantuofuService liantuofuService;

    @Autowired
    private ITcyPlatformOrderService tcyPlatformOrderService;

    // 应用配置（建议从配置文件读取）
    private static final String APP_ID = "68455149e4b0d9f2d66d3825";
    private static final String APP_SECRET = "QfLSXWkvjECYMYCn6v1VrMx4NrHtxTuXOvOPM9mbafolJq4voPrJ4aLmrgr2X8jhLZK3vyLBVInomDQ5f229emAOFTXMEoK2fIfdH6CdV6pNZUXhdGCcKfuqx01qS5kb";
    private static final String MCH_NO = "M1749373257"; // 商户号

    /**
     *
     * 根据停车场编号查询对应的规则
     */
    @GetMapping("/getCarOrder")
    public AjaxResult getCarOrder(@RequestParam(required = true) String carNo) {
        try {
            if (StringUtils.isEmpty(carNo)) {
                return AjaxResult.error("车牌号码不能为空");
            }
            return carPayService.getCarinfo(carNo);
        } catch (Exception e) {
            log.error("查询车辆信息失败，carNo: {}", carNo, e);
            return AjaxResult.error("系统内部错误，请稍后重试");
        }
    }

    /**
     * 缴费操作
     * 捷顺-支付结果通知接口
     */
    @PostMapping("/addChargeInfo")
    public AjaxResult addChargeInfo(@RequestBody Map<String, Object> params) {
        String carNo = (String) params.get("carNo");
        String orderNo = (String) params.get("orderNo");
        return carPayService.addChargeInfo(carNo, orderNo);
    }


    /**
     * 全免
     */
    @PostMapping("/freeFull")
    public AjaxResult freeFull(@RequestBody Map<String, Object> params) {
        String carNo = (String) params.get("carNo");
        String parkCode = (String) params.get("parkCode");
        return carPayService.freeFull(carNo, parkCode);
    }

    /**
     * 时长减免
     */
    @PostMapping("/addMemberRelief")
    public AjaxResult addMemberRelief(@RequestBody Map<String, Object> params) {
        String carNo = (String) params.get("carNo");
        String ticketId = (String) params.get("ticketId");
        Integer freeTime = (Integer) params.get("freeTime");
        return carPayService.addMemberRelief(carNo, ticketId, freeTime);
    }

    /**
     * 金额减免
     */
    @PostMapping("/addMemberReliefSh")
    public AjaxResult addMemberReliefSh(@RequestBody Map<String, Object> params) {
        String carNo = (String) params.get("carNo");
        String ticketId = (String) params.get("ticketId");
        Double amount = (Double) params.get("amount");
        return carPayService.addMemberReliefSh(carNo, ticketId, amount);
    }


    /**
     * 更新
     * @param tcyPlatformOrder 参数
     * @return 统一响应结果
     */
    @PostMapping("/updateTcyPlatformOrderBy")
    public AjaxResult updateTcyPlatformOrderBy(@RequestBody TcyPlatformOrder tcyPlatformOrder) {

        try {
            tcyPlatformOrderService.updateTcyPlatformOrderBy(tcyPlatformOrder);
            log.info("更新成功: {}", tcyPlatformOrder);
            return AjaxResult.success("更新成功");
        } catch (Exception e) {
            log.error("更新第三方支付订单号失败: {}", e);
            return AjaxResult.error("更新失败");
        }
    }



    /**
     * 统一下单接口（新增）
     * @param req 支付订单创建参数（包含金额、标题、描述）
     * @return 支付订单创建结果
     */
    @PostMapping("/createPayOrder")
    public AjaxResult createPayOrder(@Valid @RequestBody PayOrderCreateReq req) throws JeepayException {
        // 参数校验
        if (StringUtils.isBlank(req.getSubject())) {
            return AjaxResult.error("商品标题不能为空");
        }
        if (StringUtils.isBlank(req.getBody())) {
            return AjaxResult.error("商品描述不能为空");
        }
        if (req.getAmount() == null || req.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return AjaxResult.error("金额必须大于0元");
        }
        if (StringUtils.isBlank(req.getOpenid())) {
            return AjaxResult.error("openid不能为空");
        }

        // 金额单位转换（元转分）
        Long amountFen = req.getAmount().multiply(new BigDecimal("100")).longValue();

        // 构建支付请求
        JeepayClient jeepayClient = JeepayClient.getInstance(APP_ID, APP_SECRET);
        PayOrderCreateRequest request = new PayOrderCreateRequest();
        PayOrderCreateReqModel model = new PayOrderCreateReqModel();

        model.setMchNo(MCH_NO);
        model.setAppId(APP_ID);
        // 生成唯一商户订单号
        model.setMchOrderNo("mho" + System.currentTimeMillis());
        // 默认支付方式（可改为前端传递）
        model.setWayCode("WX_LITE");
        // 单位：分
        model.setAmount(amountFen);
        model.setCurrency("CNY");
        // 发起支付请求客户端的IP地址
        model.setClientIp("192.166.1.132");
        model.setSubject(req.getSubject());
        model.setBody(req.getBody());
        // 异步通知地址
        model.setNotifyUrl("https://tcy.mallmember.cn:19218/api/anon/paytestNotify/payOrder");
        // 渠道扩展参数
        model.setChannelExtra(channelExtra("WX_LITE",req.getOpenid()));

        request.setBizModel(model);

        // 4. 发起请求
        PayOrderCreateResponse response = jeepayClient.execute(request);

        // 5. 验证签名（注意：此处使用 APP_SECRET，与测试代码一致）
        response.checkSign(APP_SECRET);

        // 6. 判断业务结果
        if (response.isSuccess(APP_SECRET)) {
//            JSONObject result = new JSONObject();
//            result.put("payOrderId", response.getPayOrderId());
//            result.put("mchOrderNo", model.getMchOrderNo());
//            result.put("wayCode", model.getWayCode());
//            result.put("payParams", response.getPayParams());
//            return AjaxResult.success("下单成功", result);
            return AjaxResult.success("下单成功", response);
        }

        return AjaxResult.error("下单失败：" + response);
    }

    /**
     * 渠道扩展参数（示例：微信JSAPI）
     */
    private String channelExtra(String wayCode,String openid) {
        JSONObject obj = new JSONObject();
        if ("WX_LITE".equals(wayCode) || "WX_JSAPI".equals(wayCode)) {
            // 此处openId需根据业务场景获取（如从用户会话中获取）
            obj.put("openId", openid);
        }
        return obj.toString();
    }


    @ApiOperation(value= "计全支付")
    @PostMapping("/jiquan/UnifiedOrder")
    public AjaxResult unifiedOrder(@RequestBody PaymentDTO paymentDTO) {
        String result = liantuofuService.unifiedOrder(paymentDTO);
        if (StrUtil.equals("failure", result)) {
            return AjaxResult.error(result);
        } else {
            com.alibaba.fastjson2.JSONObject jsonObject = JSON.parseObject(result);
            return AjaxResult.success(jsonObject.get("data"));
        }
    }
//
//    @ApiOperation(value= "计全支付列表")
//    @PostMapping("/jiquan/UnifiedOrder/list")
//    public AjaxResult unifiedOrderList() {
//        PageDomain pageDomain = TableSupport.buildPageRequest();
//        Integer pageNum = pageDomain.getPageNum();
//        Integer pageSize = pageDomain.getPageSize();
//
//        JeepayClient jeepayClient = JeepayClient.getInstance(SysConstant.APP_ID, SysConstant.APP_SECRET, SysConstant.PAY_SITE_URL);
//        PayOrderListRequest request = new PayOrderListRequest();
//        PayOrderQueryReqModel model = new PayOrderQueryReqModel();
//        //商户号
//        model.setMchNo(SysConstant.MCH_NO);
//        //应用ID
//        model.setAppId(jeepayClient.getAppId());
//        model.setPageNumber(pageNum);
//        model.setPageSize(pageSize);
//
//        request.setBizModel(model);
//
//        try {
//            PayOrderListResponse response = jeepayClient.execute(request);
//
//            if(response.isSuccess(SysConstant.APP_SECRET)) {
//                return AjaxResult.success(response.getData());
//            }
//        } catch (JeepayException e) {
//            log.error("支付列表查询失败！", e);
//        }
//        return AjaxResult.error();
//    }

//
//
//    @ApiOperation(value = "计全支付列表（纯JSON筛选车牌号）")
//    @PostMapping("/jiquan/UnifiedOrder/list")
//    public AjaxResult unifiedOrderList(@RequestParam(required = false) String carNumber,
//                                       @RequestParam(required = false, defaultValue = "1") Integer pageNum,
//                                       @RequestParam(required = false, defaultValue = "10") Integer pageSize,
//                                       @RequestParam(required = false) String orderStatus,
//                                       @RequestParam(required = false) String startTime,
//                                       @RequestParam(required = false) String endTime ) {
////        PageDomain pageDomain = TableSupport.buildPageRequest();
////        Integer pageNum = pageDomain.getPageNum();
////        Integer pageSize = pageDomain.getPageSize();
//
//        JeepayClient jeepayClient = JeepayClient.getInstance(SysConstant.APP_ID, SysConstant.APP_SECRET, SysConstant.PAY_SITE_URL);
//        PayOrderListRequest request = new PayOrderListRequest();
//        PayOrderQueryReqModel model = new PayOrderQueryReqModel();
//
//        // 基础查询参数
//        model.setMchNo(SysConstant.MCH_NO);
//        model.setAppId(jeepayClient.getAppId());
//        model.setPageNumber(pageNum);
//        model.setPageSize(pageSize);
//
//        request.setBizModel(model);
//
//        try {
//            PayOrderListResponse response = jeepayClient.execute(request);
//
//            if (response.isSuccess(SysConstant.APP_SECRET)) {
//                // 获取原始数据
//                com.alibaba.fastjson.JSONObject data = response.getData();
//
//                // 获取原始订单列表
//                JSONArray records = data.getJSONArray("records");
//                if (records == null || records.isEmpty()) {
//                    data.put("total", 0);
//                    data.put("records", new JSONArray());
//                    return AjaxResult.success(data);
//                }
//
//
//                JSONArray filteredRecords = new JSONArray();
//                for (Object record : records) {
//                    Map<String, Object> order = (Map<String, Object>) record;
//                    // 获取订单原始金额（单位：分）
//                    Object amountObj = order.get("amount");
//                    if (amountObj != null) {
//                        // 将金额从分转换为元（除以100）
//                        BigDecimal amountInFen = new BigDecimal(amountObj.toString());
//                        if (amountInFen.compareTo(BigDecimal.ZERO) > 0) {
//                            // 分转元：除以100
//                            BigDecimal amountInYuan = amountInFen.divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
//                            // 更新订单中的金额字段
//                            order.put("amount", amountInYuan.toPlainString());
//                        }
//                    }
//                    String subject = order.get("subject").toString();
//
//                    String carNum = "";
//
//                    // 1. 优先使用前端传来的车牌号
//                    if (StringUtils.isNotBlank(carNumber)) {
//                        // 将前端传来的车牌号添加到order中
//                        carNum = carNumber;
//                        order.put("carNum", carNum);
//
//                        // 筛选subject包含该车牌号的订单
//                        if (subject != null && subject.contains(carNumber)) {
//                            filteredRecords.add(order);
//                        }
//                    }
//                    // 2. 前端未传车牌号时，从subject中提取
//                    else {
//                        if (subject != null) {
//                            int commaIndex = subject.indexOf(",");
//                            if (commaIndex > 0) {
//                                // 截取第一个逗号前的内容，并去除所有空格
//                                carNum = subject.substring(0, commaIndex).replaceAll("\\s+", "");
//                            } else {
//                                carNum = subject.replaceAll("\\s+", "");
//                            }
//                        }
//                        order.put("carNum", carNum);
//                        filteredRecords.add(order);
//                    }
//
//                    // 更新筛选后的结果
//                    data.put("records", filteredRecords);
//                    data.put("total", filteredRecords.size());
//                }
//
//                return AjaxResult.success(data);
//            }
//        } catch (JeepayException e) {
//            log.error("支付列表查询失败！", e);
//        } catch (Exception e) {
//            log.error("处理支付列表数据失败！", e);
//        }
//        return AjaxResult.error();
//    }





    @ApiOperation(value = "计全支付列表--获取全部的支付-更新订单表")
    @PostMapping("/jiquan/UnifiedOrder/updateOrderList")
    public AjaxResult unifiedOrderList() {
        log.info("【开始处理支付订单更新】进入接口 unifiedOrderList");

        JeepayClient jeepayClient = JeepayClient.getInstance(SysConstant.APP_ID, SysConstant.APP_SECRET, SysConstant.PAY_SITE_URL);
        PayOrderListRequest request = new PayOrderListRequest();
        PayOrderQueryReqModel model = new PayOrderQueryReqModel();

        try {
            // 记录请求参数
            log.info("【请求参数】MCH_NO: {}, APP_ID: {}", SysConstant.MCH_NO, jeepayClient.getAppId());

            // 获取全量支付订单数据
            model.setMchNo(SysConstant.MCH_NO);
            model.setAppId(jeepayClient.getAppId());
            model.setPageNumber(1);
            // 获取所有记录
            model.setPageSize(Integer.MAX_VALUE);

            request.setBizModel(model);
            log.info("【开始调用】Jeepay支付订单列表接口");

            PayOrderListResponse response = jeepayClient.execute(request);

            // 记录接口调用结果
            if (response.isSuccess(SysConstant.APP_SECRET)) {
                log.info("【接口响应】调用成功，状态码: {}, 数据: {}", response.getCode(), response.getData());

                // 处理金额转换和筛选
                com.alibaba.fastjson.JSONObject data = response.getData();
                JSONArray records = data.getJSONArray("records");
                if (records == null) {
                    records = new JSONArray();
                    log.warn("【数据处理】返回记录为空，初始化空数组");
                } else {
                    log.info("【数据处理】获取到 {} 条支付记录", records.size());
                }

                // 处理金额转换和筛选
                JSONArray filteredRecords = processRecords(records, null);
                log.info("【数据处理】筛选后剩余 {} 条记录", filteredRecords.size());

                // 关联并更新tcy_platform_order表
                log.info("【开始更新】准备更新平台订单表，记录数: {}", filteredRecords.size());
                int updatedCount = updatePlatformOrders(filteredRecords);
                log.info("【更新完成】成功更新 {} 条平台订单记录", updatedCount);

                // 返回全部数据，不进行分页
                Map<String, Object> result = new HashMap<>();
                result.put("records", filteredRecords);
                result.put("total", filteredRecords.size());

                log.info("【接口返回】处理完成，返回成功响应");
                return AjaxResult.success(result);
            } else {
                log.error("【接口响应】调用失败，状态码: {}, 错误信息: {}",
                        response.getCode(), response.getMsg());
                return AjaxResult.error("支付订单查询失败：" + response.getMsg());
            }
        } catch (JeepayException e) {
            log.error("【异常捕获】Jeepay接口异常，MCH_NO: {}", SysConstant.MCH_NO, e);
            return AjaxResult.error("Jeepay接口异常：" + e.getMessage());
        } catch (Exception e) {
            log.error("【异常捕获】处理支付列表数据时发生未知异常", e);
            return AjaxResult.error("处理支付数据失败：" + e.getMessage());
        } finally {
            log.info("【接口结束】unifiedOrderList 接口执行完毕");
        }
    }

    /**
     * 关联并更新tcy_platform_order表中的数据
     * @param records 支付订单记录
     * @return 更新成功的记录数
     */
    private int updatePlatformOrders(JSONArray records) {
        if (records == null || records.isEmpty()) {
            log.debug("【更新跳过】无记录需要更新");
            return 0;
        }

        int updatedCount = 0;
        log.info("【更新开始】逐条处理 {} 条支付记录", records.size());

        for (Object recordObj : records) {
            if (recordObj instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> record = (Map<String, Object>) recordObj;
                String mchOrderNo = (String) record.get("mchOrderNo");
                String payOrderId = (String) record.get("payOrderId");
                String state = String.valueOf(record.get("state"));

                if (mchOrderNo != null && !mchOrderNo.isEmpty()) {
                    try {
                        // 根据mchOrderNo查找tcy_platform_order记录
                        TcyPlatformOrder platformOrder = tcyPlatformOrderService.queryByOutTradeNo(mchOrderNo);

                        if (platformOrder != null) {
                            // 更新pay_order_id字段
                            platformOrder.setPayOrderId(payOrderId);

                            // 从subject中提取车牌号并更新
                            extractCarNumber(record);
                            String carNumber = (String) record.get("carNum");
                            if (carNumber != null) {
                                platformOrder.setCarNum(carNumber);
                            }
                            if("2".equals(state) ){
                                platformOrder.setStatus("02");
                            }

                            // 保存更新
                            tcyPlatformOrderService.updateTcyPlatformOrder(platformOrder);
                            updatedCount++;

                            if (updatedCount % 100 == 0) {
                                log.info("【更新进度】已更新 {} 条记录", updatedCount);
                            }
                        }
                    } catch (Exception e) {
                        log.error("【更新失败】mchOrderNo: {}, 错误信息: {}", mchOrderNo, e.getMessage());
                        // 继续处理其他记录，不影响整体流程
                    }
                }
            }
        }

        log.info("【更新统计】共处理 {} 条记录，成功更新 {} 条", records.size(), updatedCount);
        return updatedCount;
    }
















    @ApiOperation(value = "计全支付列表（纯JSON筛选车牌号）")
    @PostMapping("/jiquan/UnifiedOrder/list")
    public AjaxResult unifiedOrderList(@RequestBody QueryParams params) {
        JeepayClient jeepayClient = JeepayClient.getInstance(SysConstant.APP_ID, SysConstant.APP_SECRET, SysConstant.PAY_SITE_URL);
        PayOrderListRequest request = new PayOrderListRequest();
        PayOrderQueryReqModel model = new PayOrderQueryReqModel();

        // 判断是否只有分页参数
        boolean onlyPagination = hasOnlyPaginationParams(params);

        try {
            if (onlyPagination) {
                // 只有分页参数：直接使用第三方API的分页功能
                model.setMchNo(SysConstant.MCH_NO);
                model.setAppId(jeepayClient.getAppId());
                model.setPageNumber(params.getPageNum());
                model.setPageSize(params.getPageSize());

                request.setBizModel(model);
                PayOrderListResponse response = jeepayClient.execute(request);

                if (response.isSuccess(SysConstant.APP_SECRET)) {
                    // 处理第三方API返回的数据结构
                    com.alibaba.fastjson.JSONObject apiData = response.getData();

                    // 构建符合前端期望的返回结构
                    JSONObject resultData = new JSONObject();
                    resultData.put("total", apiData.getInteger("total"));
                    resultData.put("current", params.getPageNum());
                    resultData.put("size", params.getPageSize());
                    resultData.put("pages", calculateTotalPages(apiData.getInteger("total"), params.getPageSize()));

                    // 处理当前页记录
                    JSONArray records = apiData.getJSONArray("records");
                    JSONArray processedRecords = new JSONArray();

                    if (records != null) {
                        for (Object record : records) {
                            Map<String, Object> order = (Map<String, Object>) record;

                            // 处理金额转换
                            processAmount(order);

                            // 提取车牌号
                            extractCarNumber(order);

                            processedRecords.add(order);
                        }
                    }

                    resultData.put("records", processedRecords);
                    return AjaxResult.success(resultData);
                }
            } else {
                // 有筛选条件：获取全量数据后筛选
                model.setMchNo(SysConstant.MCH_NO);
                model.setAppId(jeepayClient.getAppId());
                model.setPageNumber(1);
                model.setPageSize(Integer.MAX_VALUE); // 获取所有记录

                request.setBizModel(model);
                PayOrderListResponse response = jeepayClient.execute(request);

                if (response.isSuccess(SysConstant.APP_SECRET)) {
                    // 处理金额转换和筛选
                    com.alibaba.fastjson.JSONObject data = response.getData();
                    JSONArray records = data.getJSONArray("records");
                    if (records == null){
                        records = new JSONArray();
                    }

                    // 处理金额转换和筛选
                    JSONArray filteredRecords = processRecordsOfList(records, params);

                    // 手动分页
                    JSONObject pagedData = manualPagination(filteredRecords, params.getPageNum(), params.getPageSize());
                    return AjaxResult.success(pagedData);
                }
            }
        } catch (JeepayException e) {
            log.error("支付列表查询失败！", e);
        } catch (Exception e) {
            log.error("处理支付列表数据失败！", e);
        }
        return AjaxResult.error();
    }

    /**
     * 判断是否只有分页参数
     */
    private boolean hasOnlyPaginationParams(QueryParams params) {
        return params != null &&
                params.getPageNum() > 0 &&
                params.getPageSize() > 0 &&
                StringUtils.isBlank(params.getCarNum()) &&
                StringUtils.isBlank(params.getOrderStatus()) &&
                params.getStartTime() == null &&
                params.getEndTime() == null;
        // 添加其他筛选参数判断...
    }

    /**
     * 提取车牌号
     */
    private void extractCarNumber(Map<String, Object> order) {
        String subject = (String) order.get("subject");
        if (subject != null) {
            int commaIndex = subject.indexOf(",");
            String carNum = commaIndex > 0
                    ? subject.substring(0, commaIndex).replaceAll("\\s+", "")
                    : subject.replaceAll("\\s+", "");
            order.put("carNum", carNum);
        }
    }

    /**
     * 计算总页数
     */
    private int calculateTotalPages(int total, int pageSize) {
        return (total + pageSize - 1) / pageSize;
    }



    /**
     * 处理订单记录：金额转换和多条件筛选
     */
    private JSONArray processRecords(JSONArray records, QueryParams params) {
        JSONArray filteredRecords = new JSONArray();

        // 检查records是否为空
        if (records == null) {
            return filteredRecords;
        }

        for (Object record : records) {
            // 检查record是否为空
            if (record == null) {
                continue;
            }

            Map<String, Object> order = (Map<String, Object>) record;

            // 处理金额转换
            processAmount(order);

            // 筛选逻辑
            boolean match = true;
            if (params != null) {

                // 车牌号筛选
                if (StringUtils.isNotBlank(params.getCarNum())) {
                    // 检查subject是否存在
                    Object subjectObj = order.get("subject");
                    String subject = subjectObj != null ? subjectObj.toString() : "";

                    if (!subject.contains(params.getCarNum())) {
                        match = false;
                    } else {
                        order.put("carNum", params.getCarNum());
                    }
                }
            }else {
                // 提取车牌号
                Object subjectObj = order.get("subject");
                String subject = subjectObj != null ? subjectObj.toString() : "";

                if (subject != null && !subject.isEmpty()) {
                    int commaIndex = subject.indexOf(",");
                    String carNum = commaIndex > 0
                            ? subject.substring(0, commaIndex).replaceAll("\\s+", "")
                            : subject.replaceAll("\\s+", "");
                    order.put("carNum", carNum);
                }
            }

            if (params != null) {
                // 订单状态筛选
                if (match && StringUtils.isNotBlank(params.getOrderStatus())) {
                    // 检查orderStatus是否存在
                    Object orderStatusObj = order.get("state");
                    String orderStatus = orderStatusObj != null ? orderStatusObj.toString() : "";

                    if (!orderStatus.equals(params.getOrderStatus())) {
                        match = false;
                    }
                }
            }

            if (params != null) {
                // 时间范围筛选
                if (match && params.getStartTime() != null && params.getEndTime() != null) {
                    // 检查 createdAt 是否存在
                    Object createTimeObj = order.get("createdAt");
                    String createTime = createTimeObj != null ? createTimeObj.toString() : "";

                    if (createTime.isEmpty() ||
                            !isWithinTimeRange(createTime, params.getStartTime(), params.getEndTime())) {
                        match = false;
                    }
                }
            }

            if (match) {
                filteredRecords.add(order);
            }
        }

        return filteredRecords;
    }

    /**
     * 处理订单记录：金额转换和多条件筛选
     */
    private JSONArray processRecordsOfList(JSONArray records, QueryParams params) {
        JSONArray filteredRecords = new JSONArray();

        // 检查records是否为空
        if (records == null) {
            return filteredRecords;
        }

        for (Object record : records) {
            // 检查record是否为空
            if (record == null) {
                continue;
            }

            Map<String, Object> order = (Map<String, Object>) record;

            // 处理金额转换
            processAmount(order);

            // 筛选逻辑
            boolean match = true;

            // 车牌号筛选
            if (StringUtils.isNotBlank(params.getCarNum())) {
                // 检查subject是否存在
                Object subjectObj = order.get("subject");
                String subject = subjectObj != null ? subjectObj.toString() : "";

                if (!subject.contains(params.getCarNum())) {
                    match = false;
                } else {
                    order.put("carNum", params.getCarNum());
                }
            }else {
                // 提取车牌号
                Object subjectObj = order.get("subject");
                String subject = subjectObj != null ? subjectObj.toString() : "";

                if (subject != null && !subject.isEmpty()) {
                    int commaIndex = subject.indexOf(",");
                    String carNum = commaIndex > 0
                            ? subject.substring(0, commaIndex).replaceAll("\\s+", "")
                            : subject.replaceAll("\\s+", "");
                    order.put("carNum", carNum);
                }
            }

                // 订单状态筛选
                if (match && StringUtils.isNotBlank(params.getOrderStatus())) {
                    // 检查orderStatus是否存在
                    Object orderStatusObj = order.get("state");
                    String orderStatus = orderStatusObj != null ? orderStatusObj.toString() : "";

                    if (!orderStatus.equals(params.getOrderStatus())) {
                        match = false;
                    }
                }

                // 时间范围筛选
                if (match && params.getStartTime() != null && params.getEndTime() != null) {
                    // 检查 createdAt 是否存在
                    Object createTimeObj = order.get("createdAt");
                    String createTime = createTimeObj != null ? createTimeObj.toString() : "";

                    if (createTime.isEmpty() ||
                            !isWithinTimeRange(createTime, params.getStartTime(), params.getEndTime())) {
                        match = false;
                    }
                }

            if (match) {
                filteredRecords.add(order);
            }
        }

        return filteredRecords;
    }


    /**
     * 判断时间是否在范围内
     */
    private boolean isWithinTimeRange(String time, String startTime, String endTime) {
        // 时间格式转换和比较逻辑
        // 示例：假设time、startTime、endTime为yyyy-MM-dd HH:mm:ss格式
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date target = sdf.parse(time);
            Date start = sdf.parse(startTime);
            Date end = sdf.parse(endTime);
            return !target.before(start) && !target.after(end);
        } catch (ParseException e) {
            return false;
        }
    }



    /**
     * 手动分页处理
     */
    private JSONObject manualPagination(JSONArray records, int pageNum, int pageSize) {
        JSONObject result = new JSONObject();
        int total = records.size();

        // 计算总页数
        int pages = (total + pageSize - 1) / pageSize;

        // 处理无效的页码
        if (pageNum < 1) {
            pageNum = 1;
        } else if (pageNum > pages) {
            pageNum = pages;
            if (pages == 0) {
                pageNum = 1;
            }
        }

        // 计算当前页的起始和结束索引
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);

        // 截取当前页的记录
        JSONArray currentPageRecords = new JSONArray();
        for (int i = startIndex; i < endIndex; i++) {
            currentPageRecords.add(records.get(i));
        }

        // 构造分页结果
        result.put("total", total);
        result.put("current", pageNum);
        result.put("size", pageSize);
        result.put("pages", pages);
        result.put("records", currentPageRecords);

        return result;
    }

    /**
     * 处理金额转换：分转元
     */
    private void processAmount(Map<String, Object> order) {
        Object amountObj = order.get("amount");
        if (amountObj != null) {
            try {
                BigDecimal amountInFen = new BigDecimal(amountObj.toString());
                if (amountInFen.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal amountInYuan = amountInFen.divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                    order.put("amount", amountInYuan.toPlainString());
                }
            } catch (NumberFormatException e) {
                log.error("金额转换失败", e);
            }
        }
    }




}
